package com.zhouxiaoge.springbatch.tasklet;

import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * @author 周小哥
 * @date 2021年07月09日 15点30分
 */
@Configuration
public class TaskletConfiguration {

    @Bean
    @StepScope
    public Tasklet step1Tasklet(@Value("#{jobParameters['age']}") String age) {
        return (contribution, chunkContext) -> {
            Map<String, Object> jobParameters = chunkContext.getStepContext().getJobParameters();
            Object name = jobParameters.get("name");
            System.out.println("======================step1Tasklet==========================");
            System.out.println("Step1Tasklet Hello," + name + "! age-->" + age);
            ExecutionContext executionContext = chunkContext
                    .getStepContext().getStepExecution()
                    .getJobExecution().getExecutionContext();
            executionContext.put("MyJobContext", "Exec step1Tasklet :" + LocalDateTime.now().toLocalTime().toString());
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    @StepScope
    public Tasklet step2Tasklet(@Value("#{myJobParameters['name']}") String name,
                                @Value("#{myJobParameters['fileName']}") String fileName) {
        return (contribution, chunkContext) -> {
            System.out.println("======================step2Tasklet==========================");
            System.out.println("Step2Tasklet Hello," + name + "! fileName-->" + fileName);
            Map<String, Object> jobExecutionContext = chunkContext.getStepContext().getJobExecutionContext();
            Object myJobContext = jobExecutionContext.get("MyJobContext");
            System.out.println("MyJobContext-->" + myJobContext);
            return RepeatStatus.FINISHED;
        };
    }

    @Bean
    @StepScope
    public Tasklet step3Tasklet() {
        return (contribution, chunkContext) -> {
            System.out.println("======================step3Tasklet==========================");
            return RepeatStatus.FINISHED;
        };
    }
}
